/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Deal.PersonalInformation.Logic;

import data.DAO.IDiscountCouponStore;
import data.pojo.DiscountCoupon;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

/**
 *
 * @author LiuBole
 */
public class DiscountCouponLogic extends CouponLogic{

    private IDiscountCouponStore disCouponDS = new IDiscountCouponStore();
    
    @Override
    public boolean removeCoupon(String userID, List<String> couponList, List<Integer> numList) {//优惠券及对应数量
        if(couponList == null || numList == null ){ return false; }
        if(couponList.size()!=numList.size() || couponList.isEmpty()){ return false; }
        List<DiscountCoupon> dcList = disCouponDS.searchObjectsByAttr("customerID", userID);
        List<DiscountCoupon> tempList = new ArrayList();//存放要被删除的优惠券
        for(DiscountCoupon dc:dcList){
            int loc = couponList.indexOf(dc.getId());
            if(loc!=-1){ //存在对应优惠券
                int c_num = dc.getNumber();
                int number = numList.get(loc);
                if(c_num>number){
                    dc.setNumber(c_num-number);
                } else if(c_num==number){
                    tempList.add(dc);
                } else {
                    return false; 
                }
            }
        }
        boolean valid = true;
        for(DiscountCoupon dc:tempList){
            valid &= dcList.remove(dc);
        }
        if(valid){ disCouponDS.update(dcList); }
        return valid;
    }
  
    @Override
    public Vector getCoupon(String userID) {
        List<DiscountCoupon> dcList = disCouponDS.searchObjectsByAttr("customerID", userID);
        Vector<Vector<String>> dcVector = new Vector();
        for (DiscountCoupon dc : dcList) {
            dcVector.add(toDisStringArray(dc));
        }
        return dcVector;
    }

    private Vector<String> toDisStringArray(DiscountCoupon dc) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Vector<String> list = new Vector<String>();
        
        list.add(dc.getId());
        list.add(String.valueOf(dc.getDiscount()));
        list.add(String.valueOf(dc.getNumber()));
        Date startDay = dc.getStartDay();
        Date endDay = dc.getEndDay();
        list.add(startDay==null?"":sdf.format(startDay));
        list.add(endDay==null?"":sdf.format(endDay));
        
        return list;
    }

}
